<?php
declare(strict_types=1);

namespace Modules\Admin\Service;

use HiCommon\Helper;
use HiCommon\Repository\ActivityRepository;
use HiCommon\Repository\ActivityExtendRepository;
use HiCommon\Repository\ActivityGoodsExtendRepository;
use HiCommon\Repository\GoodsRepository;
use HiCommon\Repository\StoreOrderRepository;

class ActivityService
{


    /**
     *    获取活动列表
     *    hinq 2019 10 21
     *
     **/
    public function get_list(array $arr_search)
    {
        //获取所有的活动列表
        $arr_option['with'] = ['activity_extend', 'activity_goods_extend', 'shop'];
        $arr_list = ActivityRepository::get_list((array)$arr_search, (array)$arr_option);
        $arr_list->appends($arr_search);  //将前台传过来的参数追加到集合中
        $arr_list = list_page_data($arr_list, $arr_search); //整合数据  返回的是数组
        foreach ($arr_list['data'] as $key => &$value) {
            if( $value['status']['status'] == 1 ){
                if( $value['start_time'] > time() ){
                    $value['status']['status_msg'] = '活动未开始';
                }else{
                    $value['status']['status_msg'] = '活动进行中';
                }
            }
            if ($value['status']['status'] != 1) {  //  1 正常状态  2、3  禁用   4 过期
                $value['jincheng'] = '活动已禁用';
            } else {
                $value['jincheng'] = self::get_activity_jincheng((int)$value['start_time'], (int)$value['over_time']);
            }
            $value['times'] = date('Y-m-d H:i:s', $value['start_time']) . '-' . date('Y-m-d H:i:s', $value['over_time']);
            foreach ($value['activity_extend'] as $k => $val) {
                if ($value['type']['type'] == 1) {
                    $value['activity_extend'][$k] = '满' . floor($val['price_all']) . '元减' . floor($val['price']) . '元';
                } else {
                    $value['activity_extend'][$k] = '满' . floor($val['price_all']) . '元打' . floor($val['price']) . '折';
                }
            }
            $ids = '';  //所有活动关联的商品信息
            $model_count = 0;
            foreach ($value['activity_goods_extend'] as $k => $vo) {
                if (!empty($vo['goods'])) {
                    $ids .= ',' . $vo['goods'];
                }
                $model_count++;
            }
            $count = 0;
            if (!empty($ids)) {
                $count = count(explode(',', trim($ids, ',')));
            }
            $value['goods_count'] = $count;
            $value['model_count'] = $model_count;
            unset($value['activity_goods_extend']);
        }

        return hello_success('成功', $arr_list);
    }


    /**
     *    添加活动数据
     *    hinq 2019 10 21
     *
     **/
    public function add_one(array $arr_input)
    {

        \DB::beginTransaction();
        try { //添加

            //验证提交过来的数据
            $res = self::check_data((array)$arr_input);
            if ($res['state'] == 1) {
                return $res;
            }
            $data['img'] = $arr_input['img'];
            $data['title'] = $arr_input['title'];
            $data['type'] = $arr_input['type'];
            $data['content'] = $arr_input['content'];
            $times = explode(' - ', $arr_input['times']);
            $data['start_time'] = strtotime($times[0]);   //开始时间是当天时间的第一秒开始
            $data['over_time'] = strtotime($times[1] . '23:59:59');    //结束时间默认是当天的最后一秒
            $data['status'] = 1;
            $data['repairstore_id'] = 1;  //1:平台   2：商户

            $res = ActivityRepository::add_one((array)$data);
            $temp['activity_id'] = $res->id;
            $res2 = true;
            foreach ($arr_input['price_all'] as $key => $value) {
                if ($arr_input['type'] == 1) {  //满减
                    if ( $arr_input['price'][$key] > $value) {     //优惠金额  》 最低消费金额
                        return hello_error('优惠金额设置错误');
                    }
                }
                if (!empty($value)) {
                    $temp['price_all'] = round( $value , 2 );
                    $temp['price'] = round( $arr_input['price'][$key] , 2);
                    $res2 = ActivityExtendRepository::add_one((array)$temp);
                }
            }
            if ($res && $res2) {
                \DB::commit();
            }
            return hello_success('添加成功', $res);
        } catch (\Exception $exception) {
            \DB::rollBack();
            return ['state' => 1, 'msg' => $exception->getMessage()];
        }

    }

    /**
     *    验证数据有效性
     *    hinq 2019 10 21
     *
     **/
    public function check_data(array $data)
    {

        if (empty($data['img'])) {
            return hello_error('请上传背景图片');
        }

        if (empty($data['title'])) {
            return hello_error('请填写活动名称');
        }
        if (mb_strlen($data['title']) > 50) {
            return hello_error('活动名称最多50个字符');
        }
        if (empty($data['type'])) {
            return hello_error('请选择活动类型');
        }
        //                                    删除数组中为空的键值对
        if ($data['type'] == 1 && empty(hi_array_del_null($data['price_all']))) {
            return hello_error('请设置满减信息');
        }
        //                                    删除数组中为空的键值对
        if ($data['type'] == 2 && empty(hi_array_del_null($data['price_all']))) {
            return hello_error('请设置满折信息');
        }
        if (empty($data['content'])) {
            return hello_error('请填写活动公告');
        }
        if (empty($data['times'])) {
            return hello_error('请设置活动有效期');
        }
        //   当前用户自己的活动  并且在有效的时间范围内
        $arr_where = ['repairstore_id' => 1, 'status' => 1];
        $times = explode(' - ', $data['times']);
        //不允许添加当天的活动
        if( (int) strtotime( $times[0] ) < time() ){
            return hello_error('活动时间不能小于当前时间');
        }
        if( (int) strtotime( $times[0] ) > (int) strtotime( $times[1] ) ){
            return hello_error('活动的开始时间不能大于结束时间');
        }
        $count = ActivityRepository::get_count_by_where_to_time((int)strtotime($times[0]), (array)$arr_where, (int)$data['id']);
        if ($count > 0) {
            return hello_error('该时间段已有活动，请重新设置活动时间');
        }
        $count = ActivityRepository::get_count_by_where_to_time((int)strtotime($times[1]), (array)$arr_where, (int)$data['id']);
        if ($count > 0) {
            return hello_error('该时间段已有活动，请重新设置活动时间');
        }
        return $data;
    }

    /**
     *    添加活动的商品信息
     *    hinq 2019 10 21  3700   920
     *
     **/
    public function get_goods_list(int $nId)
    {
        //获取当前用户的商户id
        $shop_id = get_shop_id();
        if (empty($shop_id)) {
            return [];
        }
        //获取当前活动已设置的模块
        $arr = self::get_goods_list_to_activity((int)$nId, false);
        $ids = '';
        foreach ($arr as $key => $value) {
            $ids .= $value['goods'] . ',';
        }

        $ids = array_unique(explode(',', trim($ids, ',')));

        $arr_where2['where'] = ['repairstore_id' => $shop_id, 'type' => 1, 'status' => 1];
        $arr_where2['field'] = ['id', 'pic_url', 'name'];
        $arr_map = [];
        if (count($ids) > 0) {
            $arr_map['field'] = 'id';
            $arr_map['ids'] = $ids;
            $arr_list = GoodsRepository::get_wherenotin_activity_to_goods((array)$arr_where2, (array)$arr_map)->toArray();
            return hello_success('获取成功', $arr_list);
        }
        $arr_list = GoodsRepository::get_wherein_activity_to_goods((array)$arr_where2, (array)$arr_map)->toArray();
        return hello_success('获取成功', $arr_list);
    }


    public function goods_list_store(array $arr_input)
    {
        //获取当前活动信息
        $arr_option['field'] = ['id','start_time','over_time'];
        $activity_info = ActivityRepository::get_one( (int) $arr_input['id'] , (array) $arr_option );
        if( empty( $activity_info->first() ) ){
            return hello_error('参数错误');
        }
        $activity_info = $activity_info->toarray();

        if( $activity_info['start_time'] < time() ){
            //获取当前活动是否添加过商品
            $count = ActivityGoodsExtendRepository::get_count_by_where( ['activity_id'=>$activity_info['id']]);
            if( $count > 0 ){   //进行中的活动 但是没有添加商品  允许添加商品
                return hello_error('参与活动期间的活动不支持修改内容');
            }
        }

        $goods_ids = implode(',', array_unique($arr_input['goods_list']));

        $data['activity_id'] = $arr_input['id'];
        $data['name'] = $arr_input['name'];
        $data['goods'] = $goods_ids;
        $res = ActivityGoodsExtendRepository::add_one((array)$data);
        //将设置的商品设置为活动商品
//        GoodsRepository::change_status((array)array_unique($arr_input['goods_list']), (array)['type' => 3]);
        if (empty($res)) {
            return hello_error('添加失败');
        }
        return hello_success('添加成功');
    }


    /**
     *    获取指定活动已经添加的商品信息
     *    hinq 2020 3 12
     *
     **/
    public function get_goods_list_to_activity(int $nId, bool $is_goods = true)
    {
        try {
            if (empty($nId)) {
                return hello_error('参数错误');
            }
            //获取当前活动的主要信息
            $arr_info = ActivityRepository::get_one($nId);
            if (empty($arr_info->first())) {
                return hello_error('参数错误');
            }

            $data['is_show'] = false;
            if ($arr_info['repairstore_id'] == 1) {   //平台只能查看店铺设置的信息 不可以设置修改平台设置的商品信息
                $data['is_show'] = true;
            }
            $arr_where['where'] = ['activity_id' => $nId];
            $arr_where['order'] = ['key' => 'created_at', 'value' => 'asc'];
            $arr_where['field'] = ['id', 'activity_id', 'name', 'goods'];
            //获取当前活动已设置的商品信息
            $arr_list = ActivityGoodsExtendRepository::get_all((array)$arr_where)->toArray();
            $ids = '';
            // 注意  php处理数组的速度很快  多次查询数据库的效率低下
            if (count($arr_list) > 0 && $is_goods) {
                foreach ($arr_list as $key => $value) {
                    $ids .= $value['goods'] . ',';
                }
                if (!empty($ids)) {
                    $ids = explode(',', trim($ids, ','));
                    $arr_option['field'] = ['id', 'pic_url', 'name'];
                    $map = ['field' => 'id', 'ids' => $ids];
                    $arr_goods = GoodsRepository::get_wherein_activity_to_goods((array)$arr_option, (array)$map)->toArray();
                }
                foreach ($arr_list as $key => $value) {
                    foreach ($arr_goods as $k => $vo) {
                        $ids = explode(',', $value['goods']);
                        if (in_array($vo['id'], $ids)) {
                            $arr_list[$key]['goods_info'][] = $vo;
                        }
                    }
                }
            }
            $data['data'] = $arr_list;
            return $data;
        } catch (\Exception $exception) {
            \DB::rollBack();
            return ['state' => 1, 'msg' => $exception->getMessage()];
        }
    }


    /**
     *    强制禁用活动（不可恢复到正常状态） 当前操作只允许平台
     *    hinq 2019 10 23
     *
     **/
    public function change_status(int $nId)
    {
        try {
            if (empty($nId)) {
                return hello_error('参数错误');
            }
            //获取当前活动的状态
            $arr_option['field'] = ['id', 'status'];
            $activity_info = ActivityRepository::get_one((int)$nId, (array)$arr_option)->toArray();
            if (count($activity_info) == 0) {
                return hello_error('参数错误');
            }
            if ($activity_info['status'] != 1) {
                return hello_error('该活动已禁用');
            }
            $data['status'] = 3;   //平台禁用
            $data['id'] = $nId;
            $res = ActivityRepository::edit_one($data);
            if (empty($res)) {
                return hello_error('禁用失败');
            }
            return hello_success('禁用成功');
        } catch (\Exception $exception) {
            return ['state' => 1, 'msg' => $exception->getMessage()];
        }
    }


    /**
     *    删除活动的商品模块
     *    hinq 2019 10 23
     *
     **/
    public function del_one(int $nId)
    {
        try {
            if (empty($nId)) {
                return hello_error('参数错误');
            }
            $arr_option['field'] = ['id', 'goods'];
            $arr_info = ActivityGoodsExtendRepository::get_one((int)$nId, (array)$arr_option)->toArray();
            if (count($arr_info) > 0) {
                //将商品的活动属性修改为普通商品属性
                GoodsRepository::change_status((array)explode(',', trim($arr_info['goods'], ',')), (array)['type' => 1]);
            }
            $res = ActivityGoodsExtendRepository::delete_one($nId);
            if (empty($res)) {
                return hello_error('删除失败');
            }
            return hello_success('删除成功');
        } catch (\Exception $exception) {
            \DB::rollBack();
            return ['state' => 1, 'msg' => $exception->getMessage()];
        }
    }

    /**
     *  通过活动的开始时间和结束时间计算当前活动的进程
     *  hinq 2020 3 12
     *  超两处地方都是用的逻辑   提取出来
     **/
    public function get_activity_jincheng(int $start, int $over)
    {
        $jincheng = '未知';
        if ($start > time()) {   //活动开始时间大于当前时间
            $jincheng = '未开始';
        }
        if ($start < time() && $over > time()) {   //活动开始时间大于当前时间 小于结束时间
            $jincheng = '进行中';
        }
        if ($over < time()) {   //活动结束时间小于当前时间
            $jincheng = '已结束';
        }
        return $jincheng;
    }


    /**
     *    详细信息获取指定的活动
     *    hinq 2019 10 25
     *
     **/
    public function get_one(int $nId)
    {
        try {
            if (empty($nId)) {
                return ['state' => 1, 'msg' => ''];
            }
            //获取指定的活动数据
            $arr_option['field'] = ['id','img','title','type','content','start_time','over_time','created_at','status','repairstore_id'];
            $arr_option['with'] = ['activity_extend'];
            $arr_list = ActivityRepository::get_one((int)$nId, (array)$arr_option)->toArray();
            if (count($arr_list) < 1) {
                return [];
            }
            $arr_list['msg'] = self::get_activity_jincheng((int)$arr_list['start_time'], (int)$arr_list['over_time']);
            $arr_list['times'] = date('Y-m-d H:i:s', $arr_list['start_time']) . ' - ' . date('Y-m-d H:i:s', $arr_list['over_time']);
            //统计当前活动订单信息
            $arr_options = ['order_type' => 2, 'activity_id' => $nId, 'pay_status' => 2];
            $arr_order = StoreOrderRepository::get_user_to_order_count((array)$arr_options)->toArray();
            //统计当前活动参与的人数（同一用户不管下单多少都只算一次）
            $participant_num = StoreOrderRepository::count_participant_activity_user((array)$arr_options);
            $data = [
                'day' => (string)round(($arr_list['over_time'] - $arr_list['start_time']) / 3600 / 24),   //活动持续的天数
                'order_total' => $arr_order[0]['total'],      //订单总数
                'profit' => (string)floatval($arr_order[0]['pay_amount']),      //盈利金额
                'user_num' => $participant_num,      //参与人数
            ];
            $temp = [
                'info' => $arr_list,
                'data' => $data,
            ];
            return $temp;
        } catch (\Exception $exception) {
            return ['state' => 1, 'msg' => $exception->getMessage()];
        }
    }


    /**
     *    活动详情获取与活动相关的订单
     *    hinq 2019 10 26
     *
     **/
    public function get_order_list(int $nId)
    {
        try {
            // order_type  2:活动商品  1：普通商品
            $arr_option['where'] = ['order_type' => 2, 'activity_id' => $nId, 'pay_status' => 2];
            $arr_option['field'] = ['id','order_no','pay_status','order_amount','pay_time','pay_amount','coupon_price','status','user_id','pay_type','created_at'];
            $arr_option['with'] = ['getUser'];
            $arr_list = StoreOrderRepository::get_list((array)$arr_option)->toArray();
            foreach ($arr_list['data'] as $key => &$value) {
                $value['user_name'] = $value['get_user']['nickname'];
                $value['phone'] = $value['get_user']['phone'];
                $value['pay_status'] = $value['status'] == 1 ? '已支付': '未支付';
                $value['pay_type'] = $value['pay_type'] == 1 ? '微信': '支付宝';
                $value['status_msg'] = $value['status']['name'];
                unset( $value['get_user'] );
            }
            //前台框架layui.table 要求返回的固定数据格式
            return ['code' => 0, 'msg' => '', 'data' => $arr_list['data'], 'count' => $arr_list['total']];
        } catch (\Exception $exception) {
            return ['state' => 1, 'msg' => $exception->getMessage()];
        }
    }

    /**
     *  获取指定商品是否绑定活动
     *  hinq 2020 5 29
     *
     **/
    public function goods_is_del( int $nId ){
        try{
            if( empty( $nId ) ){
                return hello_error('参数错误');
            }
            //获取所有未开始 或进行中的活动信息
            $arr_option['where'] = ['status' => 1];
            $arr_option['with'] = ['activity_goods_extend'];
            $arr_list = ActivityRepository::get_all( $arr_option )->toarray();
            $goods_ids = null;
            foreach ( $arr_list as $key => $vo ){
                foreach ( $vo['activity_goods_extend'] as $k => $v ){
                    $goods_ids .= ',' . $v['goods'];
                }
            }
            $goods_ids = explode( ',' , trim( $goods_ids , ',') );
            if( in_array(  $nId , $goods_ids ) ){
                return hello_error('当前商品已参与活动，不可删除');
            }
            return  hello_success('ok');
        }catch (\Exception $exception){
            return hello_error( $exception->getMessage() );
        }
    }



}
